<script setup>
    import { ref,computed,onBeforeUnmount } from 'vue';
    import emitter from "../../../utils/bus";

    const cartItems = ref([]);
    let product=ref();

    //注册事件监听器 on('事件名',处理函数)
    emitter.on('addToCart',(data) => {
        product=data.msg;
        const cartItem = cartItems.value.find(item => item.id === product.id)
        if(cartItem) {
            cartItem.number++
        } else {
            cartItems.value.push({...product, number: 1})
        }
    });
    //在组件卸载之前进行必要的资源清理和状态管理，避免潜在的内存泄露
    onBeforeUnmount(() => {
        emitter.off('addToCart') //移除事件监听器
    });

    const removeFromCart = (item) => {
        const index = cartItems.value.indexOf(item)
        if(index > -1) {
            cartItems.value.splice(index, 1)
        }
    }

    const handleChange = (item) => {
        if(item.number <= 0) {
            removeFromCart(item)
        }
    }

    const totalPrice = computed(() => {
        return cartItems.value.reduce((total, item) => {
            return total + item.price * item.number
        }, 0)
    })
</script>

<template>

    <el-card style="margin-top: 20px;">
        <h2>购物车</h2>
        <div v-if="cartItems.length>0">
            <div v-for="(item,i) in cartItems" :key="i">
                <p style="display: flex;flex-direction: row;align-items: center;">
                    <img :src="item.img" style="width: 30%;margin-right: 5px;"/>
                    {{item.name}}
                </p>
                <p>
                    单价：￥{{item.price}}&nbsp;&nbsp;&nbsp;
                    <el-input-number v-model="item.number" :min="0" :max="item.stock" @change="handleChange(item)" />
                </p>
                <el-divider style="margin: 10px 0;"/>
            </div>
        </div>
        <div v-else>
            <el-empty description="暂无商品"></el-empty>
        </div>
        <p>总价：￥{{totalPrice}}</p>
    </el-card>

</template>

<style scoped>   
    a{text-decoration: none;}
</style>

